package com.wb.adutils.ads.pangle

import android.app.Activity
import android.view.View
import android.view.ViewGroup
import android.widget.RelativeLayout
import com.bytedance.sdk.openadsdk.*
import com.wb.adutils.AdBaseLoader
import com.wb.adutils.db.AdEntity
import com.wb.adutils.tools.AdConstants
import com.wb.adutils.tools.LogC
import java.lang.Exception


class PangleBannerAdUtils(val adEntity: AdEntity?): AdBaseLoader(adEntity) {

    private var mTTBannerViewAd: TTNativeExpressAd? = null

    override fun excLoadAd(activity: Activity) {
        try {
            // 判断当前是否存在config 配置 ，如果存在直接加载广告 ，如果不存在则注册config加载回调
            LogC.e("pangle -> banner ->  准备加载广告")
            val mTTAdNative = TTAdSdk.getAdManager().createAdNative(activity)
            val adSlot = AdSlot.Builder()
                .setCodeId(adEntity?.adUnit) //广告位id
                .setSupportDeepLink(false)
                .setAdCount(count) //请求广告数量为1到3条
                .setExpressViewAcceptedSize(width * 1f, height * 1f)  //期望模板广告view的size,单位dp
                .setAdLoadType(TTAdLoadType.LOAD) //推荐使用，用于标注此次的广告请求用途为预加载（当做缓存）还是实时加载，方便后续为开发者优化相关策略
                .build()

            //请求广告
            mTTAdNative.loadBannerExpressAd(adSlot, object : TTAdNative.NativeExpressAdListener {
                //广告请求失败
                override fun onError(code: Int, message: String) {
                    LogC.e("pangle -> banner -> onError...code=$code, msg=$message")
                    excAdLoadFail(code)
                }

                //广告请求成功
                override fun onNativeExpressAdLoad(ads: List<TTNativeExpressAd>) {
                    LogC.e("pangle -> banner -> onNativeExpressAdLoad..." + ads.size)
                    if (timeoutDisposable?.isDisposed == true) { // 已超时
                        LogC.e("pangle -> banner ->  onAdLoaded...但已超时")
                        return
                    }
                    LogC.e("pangle -> banner ->  onAdLoaded...")
                    timeoutDisposable?.dispose()
                    mTTBannerViewAd = ads.first()
                    if (mTTBannerViewAd == null) {
                        LogC.e("pangle -> banner ->  onAdLoaded...adView is null")
                        listener?.onAdLoadFail(AdConstants.AD_ERROR_CODE_INTERNAL)
                        release()
                    } else {
                        isAdLoadSuccess = true
                        listener?.onAdLoaded(mTTBannerViewAd)
                    }
                }
            })
            isAdLoadSuccess = false
        } catch (e: Exception) {
            e.printStackTrace()
            timeoutDisposable?.dispose()
            listener?.onAdLoadFail(AdConstants.AD_ERROR_CODE_EXCEPTION)
            release()
        }
    }

    override fun showAd(adRoot: ViewGroup?){
        LogC.e("pangle -> banner ->  showAd...")
        if (adRoot == null || adRoot.context == null) {
            release()
            LogC.e("pangle -> banner ->  showAd...adRoot is null")
            return
        }

        adRoot.removeAllViews()
        if (!isAdLoadSuccess) {
            LogC.e("pangle -> banner ->  showAd isAdLoadSuccess is false...")
            adRoot.visibility = View.GONE
            listener?.onAdLoadFail(AdConstants.AD_ERROR_CODE_NOT_LOAD_SUCCESS)
            release()
            return
        }

        mTTBannerViewAd?.setExpressInteractionListener(object : TTNativeExpressAd.ExpressAdInteractionListener {
            //广告点击回调
            override fun onAdClicked(view: View, type: Int) {
                listener?.onAdClicked()
            }

            //广告展示回调
            override fun onAdShow(view: View, type: Int) {
                listener?.onAdDisplay()
            }

            //广告渲染失败回调
            override fun onRenderFail(view: View, msg: String, code: Int) {
                LogC.e("pangle -> banner -> onRenderFail...")
                listener?.onAdLoadFail(code)
                release()
            }

            //广告渲染成功回调
            override fun onRenderSuccess(view: View, width: Float, height: Float) {
                LogC.e("pangle -> banner ->  showAd  添加到view...")
                adRoot.visibility = View.VISIBLE
                val layoutParams = RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT)
                layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT)
                adRoot.addView(view, layoutParams)
            }
        })
        //使用默认模板中默认dislike弹出样式
        mTTBannerViewAd?.setDislikeCallback(findActivity(adRoot.context), object : TTAdDislike.DislikeInteractionCallback {
            override fun onShow() {}
            override fun onCancel() {
                listener?.onAdLoadFail(AdConstants.AD_ERROR_CODE_USER_CANCEL)
                release()
            }
            override fun onSelected(position: Int, value: String, enforce: Boolean) {}
        })
        // 渲染广告
        mTTBannerViewAd?.render()
    }



    override fun release(){
        super.release()
        mTTBannerViewAd?.destroy()
        mTTBannerViewAd = null
    }
}